package com.zw.yzk.kabu.management;

import android.support.v7.app.AppCompatActivity;

import java.util.Stack;

/**
 * Created by zhanwei on 2016/12/23.
 */

public class ActivityManager {

    private Stack<AppCompatActivity> activityStack;

    private static ActivityManager instance;

    private ActivityManager() {

    }

    public static ActivityManager getInstance() {
        if (instance == null) {
            synchronized (ActivityManager.class) {
                if (instance == null) {
                    instance = new ActivityManager();
                }
            }
        }
        return instance;
    }

    /**
     * 获取最后一个入栈的Activity
     * @return activity
     */
    public AppCompatActivity getTopActivity() {
        if (activityStack == null) {
            return null;
        }
        return activityStack.lastElement();
    }

    /**
     * 获取指定Activity实例
     * @param cls activity类
     * @return activity
     */
    public AppCompatActivity getActivity(Class<?> cls) {
        if (activityStack == null) {
            return null;
        }
        AppCompatActivity returnActivity = null;
        for (AppCompatActivity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                returnActivity = activity;
            }
        }
        return returnActivity;
    }

    /**
     * 添加Activity到栈
     * @param activity 添加对象
     */
    public void addActivity(AppCompatActivity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }

    /**
     * 将Activity从栈中移除
     * @param activity 移除对象
     */
    public void removeActivity(AppCompatActivity activity) {
        if (activityStack == null || activityStack.isEmpty() || activity == null) {
            return;
        }
        activityStack.remove(activity);
    }

    /**
     * 结束指定的Activity
     * @param activity 结束Activity
     */
    public void finishActivity(AppCompatActivity activity) {
        if (activity != null && activityStack != null) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     * @param cls 指定Activity
     */
    public void finishActivity(Class<?> cls) {
        if (activityStack == null) {
            return;
        }
        AppCompatActivity deleteActivity = null;
        for (AppCompatActivity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                deleteActivity = activity;
            }
        }

        finishActivity(deleteActivity);
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }
}
